<template>
  <PublicPage bgColor="#F5F5F5">
    <template v-if="pageType === PageTypeEnum.AUDIT">
      <view class="py-4 text-center">
        <view
          class="text-base font-bold"
          :class="'u-' + getApstatusData(formData.apStatus as string).type">
          {{ getApstatusData(formData.apStatus as string).text }}
        </view>
        <view v-if="formData.apStatus === ExpertApStatusEnum.ERROR">
          {{ formData.apText }}
        </view>
        <view
          v-else-if="formData.apStatus === ExpertApStatusEnum.APPLIED"
          class="pt-1 u-tips-color">
          已等待{{ awaitTime(formData.createTime as string).desc }}
        </view>
      </view>

      <view v-if="formData.submitName" class="px-3 py-3 mb-3 bg-white">
        <view class="pb-2 text-base font-bold">医生入驻申请</view>
        <view class="flex py-1">
          <view class="w-[150rpx] u-tips-color">提交时间:</view>
          <view>{{ formData.createTime }}</view>
        </view>
        <view class="flex py-1">
          <view class="w-[150rpx] u-tips-color">提交人:</view>
          <view v-if="formData.submitDeptName" class="pr-2">
            {{ formData.submitDeptName }}
          </view>
          <view class="u-primary">{{ formData.submitName }}</view>
        </view>
      </view>
    </template>

    <u-form
      labelPosition="left"
      :model="formData"
      :rules="rules"
      :labelWidth="100"
      ref="form"
      errorType="border-bottom">
      <view class="px-4 pt-3 bg-white">
        <view class="title">基础信息</view>
        <u-form-item label="姓名" prop="userName" required>
          <up-input
            v-model="formData.userName"
            :disabled="pageType === PageTypeEnum.AUDIT"
            disabledColor="#FFF"
            border="none"
            inputAlign="right"
            placeholder="请输入医生姓名"></up-input>
        </u-form-item>
        <u-form-item label="性别" prop="sex">
          <SelectPick
            v-model="formData.sex"
            :dictList="sexOptions"
            placeholder="请选择性别"
            :disabled="pageType === PageTypeEnum.AUDIT"
            @open="getSexOptions" />
        </u-form-item>
        <u-form-item label="手机号" prop="mobile" required>
          <up-input
            v-model.trim="formData.mobile"
            :disabled="pageType !== PageTypeEnum.ADD"
            disabledColor="#FFF"
            border="none"
            inputAlign="right"
            placeholder="请输入手机号"></up-input>
        </u-form-item>
        <u-form-item label="所属机构" prop="comId" required>
          <view
            class="text-[30rpx] w-full flex justify-end items-center"
            @click="goSelectCom">
            <text :class="{ 'u-light-color': !selectedCom.cname }">
              {{ selectedCom.cname || '请选择机构' }}
            </text>
            <i
              v-if="pageType !== PageTypeEnum.AUDIT"
              class="iconfont rightArrow">
              &#xe60d;
            </i>
          </view>
        </u-form-item>
        <u-form-item label="所属科室" prop="deptId">
          <SelectPick
            v-model="formData.deptId"
            :dictList="deptOptions"
            :disabled="!selectedCom.id || pageType === PageTypeEnum.AUDIT"
            placeholder="请先选择机构再选择科室"
            @open="getDeptOptions" />
        </u-form-item>
        <u-form-item label="医生电子签名" prop="prescriptionSign">
          <view class="text-[30rpx] w-full flex justify-end items-center" @click="goSetSign">
            <image
              v-if="prescriptionSign"
              :src="prescriptionSign"
              style="width: 200rpx; height: 100rpx;"
              mode="widthFix" />
            <template v-else>
              <text class="u-light-color">未设置签名</text>
              <i class="iconfont rightArrow">&#xe60d;</i>
            </template>
          </view>
        </u-form-item>
        <u-form-item
          label="医生证照（用于展示给患者和PAD上浏览）"
          labelWidth="100%"
          :customStyle="{ 'flex-direction': 'column' }"
          :borderBottom="false"
          prop="headimg">
          <UploadImg
            v-model="formData.headimg"
            name="headimg"
            bottom-tips="只支持.jpg.png 格式，400*400尺寸"
            :disabled="pageType === PageTypeEnum.AUDIT"></UploadImg>
        </u-form-item>
      </view>

      <view class="px-4 pt-3 mt-3 bg-white">
        <view class="title">认证信息</view>
        <u-form-item label="医生职称" prop="postId" required>
          <SelectPick
            v-model="formData.postId"
            :dictList="postOptions"
            placeholder="请选择医生职称"
            :disabled="pageType === PageTypeEnum.AUDIT"
            @open="getPostOptions" />
        </u-form-item>
        <u-form-item
          label="医生身份证"
          labelWidth="100%"
          :customStyle="{ 'flex-direction': 'column' }"
          prop="idcard2"
          required>
          <view class="block">
            <view class="flex">
              <UploadImg
                v-model="formData.idcard1"
                name="idcard1"
                tips="身份证正面"
                :width="158"
                :height="100"
                bottom-tips="只支持.jpg.png 格式"
                :disabled="pageType === PageTypeEnum.AUDIT"></UploadImg>
              <UploadImg
                v-model="formData.idcard2"
                name="idcard2"
                tips="身份证反面"
                :width="158"
                :height="100"
                :disabled="pageType === PageTypeEnum.AUDIT"></UploadImg>
            </view>
          </view>
        </u-form-item>
        <u-form-item
          label="医师资格证书"
          labelWidth="100%"
          :customStyle="{ 'flex-direction': 'column' }"
          prop="qualificationCertificate"
          required>
          <UploadImg
            v-model="formData.qualificationCertificate"
            name="qualificationCertificate"
            tips="医师资格证书"
            bottom-tips="只支持.jpg.png 格式"
            :disabled="pageType === PageTypeEnum.AUDIT"></UploadImg>
        </u-form-item>
        <u-form-item
          label="中医医师执业证书（或西学中2年以上证书）"
          labelWidth="100%"
          :customStyle="{ 'flex-direction': 'column' }"
          :borderBottom="false"
          prop="chineseMedicineQualification">
          <UploadImg
            v-model="formData.chineseMedicineQualification"
            name="chineseMedicineQualification"
            tips="上传执业证书"
            bottom-tips="只支持.jpg.png 格式"
            :disabled="pageType === PageTypeEnum.AUDIT"></UploadImg>
        </u-form-item>
      </view>
    </u-form>

    <FixedButton v-if="pageType === PageTypeEnum.AUDIT" placeholder>
        <!-- v-if="formData.apStatus === ExpertApStatusEnum.ERROR" -->
      <u-button
        type="primary"
        :loading="loading"
        @click="goEditExpert">
        重新修改资料
      </u-button>
    </FixedButton>
    <FixedButton v-else-if="pageType === PageTypeEnum.EDIT" placeholder>
      <u-button type="primary" :loading="loading" @click="submit">
        {{ formData.apStatus === ExpertApStatusEnum.ERROR ? '重新提交审核' : '确认修改信息' }}
      </u-button>
    </FixedButton>
    <div v-else class="p-4">
      <u-button type="primary" :loading="loading" @click="submit">
        提交注册审核
      </u-button>
    </div>
  </PublicPage>
</template>

<script setup lang="ts">
import FixedButton from '@/components/fixedButton.vue'
import UploadImg from '@/components/upload.vue'
import {
  addExpert,
  apExpertDetails,
  expertInfo,
  updateExpert
} from '@/api/expert'
import { ExpertInfoTypes } from '@/types/expert'
import SelectPick from '@/components/selectPick.vue'
import { dictData, DictItemTypes } from '@/api/dict'
import { companyDetails, getDeptList, getPostList } from '@/api/organization'
import { useExpertStore } from '@/stores/expert'
import { ExpertApStatusEnum, PageTypeEnum } from '@/utils/enums'
import { awaitTime } from '@/utils'
import { setRefreshRouters } from "@/hooks/refreshPage";

const expertStore = useExpertStore()
const { selectedCom, prescriptionSign } = storeToRefs(expertStore) // 获取已选择机构+医生签名

const getApstatusData = (apStatus: string) => {
  switch (apStatus) {
    case ExpertApStatusEnum.ERROR:
      return {
        text: '已驳回',
        type: 'error'
      }
    case ExpertApStatusEnum.SUCCEED:
      return {
        text: '已通过',
        type: 'primary'
      }
    case ExpertApStatusEnum.APPLIED:
      return {
        text: '平台审核中',
        type: 'success'
      }
    default:
      return {
        text: '未认证',
        type: 'warning'
      }
  }
}

const formData = ref<ExpertInfoTypes>({
  userName: '',
  sex: undefined,
  mobile: '',
  com: '',
  comId: '',
  deptId: undefined,
  postId: undefined,
  prescriptionSign: '', // 医生电子签名
  headimg: '', // 医生头像
  idcard1: '', // 身份证正面
  idcard2: '', // 身份证反面
  qualificationCertificate: '', // 医生资格证书
  chineseMedicineQualification: '', // 中医资格证书

  // 下面是审核才有返回的参数
  apStatus: undefined,
  createTime: undefined,
  apText: undefined,
  submitDeptName: undefined,
  submitName: undefined
})

const rules = reactive({
  userName: [
    {
      type: 'string',
      required: true,
      message: '请输入医生姓名',
      trigger: ['blur', 'change']
    }
  ],
  mobile: [
    {
      type: 'string',
      required: true,
      message: '请输入手机号',
      trigger: ['blur', 'change']
    },
    {
      pattern: /^(\+?86-?)?1[3-9]\d{9}$|^(\+?852-?)?[569]\d{7}$|^(\+?853-?)?[6]\d{7}$|^(\+?886-?)?[0-9]\d{8}$/, 
      message: '请输入有效的手机号', 
      trigger: 'blur'
    }
  ],
  comId: [
    {
      type: 'number',
      required: true,
      message: '请选择所属机构',
      trigger: ['change']
    }
  ],
  postId: [
    {
      type: 'number',
      required: true,
      message: '请选择医生职称',
      trigger: ['change']
    }
  ],
  idcard1: [
    {
      type: 'string',
      required: true,
      message: '请上传身份证正面',
      trigger: ['change']
    }
  ],
  idcard2: [
    {
      type: 'string',
      required: true,
      message: '请上传身份证反面',
      trigger: ['change']
    }
  ],
  qualificationCertificate: [
    {
      type: 'string',
      required: true,
      message: '请上传医生资格证书',
      trigger: ['change']
    }
  ]
})

// 提交注册 || 修改医生信息
const loading = ref(false)
const _that = getCurrentInstance()
const submit = () => {
  formData.value.prescriptionSign = prescriptionSign.value as string;
  console.log(JSON.parse(JSON.stringify(unref(formData))), '提交的数据');
  (_that?.refs.form as any).validate().then(() => {
      loading.value = true
      setTimeout(async () => {
        if (unref(pageType) === PageTypeEnum.EDIT) {
          // 修改
          await updateExpert(unref(formData)).finally(() => {
            loading.value = false
          })
          // 刷新详情页和列表页
          setRefreshRouters(['/pages/expert/expertDetail', '/pages/expert/expert']);
        } else {
          // 新增
          await addExpert(unref(formData)).finally(() => {
            loading.value = false
          })
          // 刷新列表页
          setRefreshRouters(['/pages/expert/expert']);
        }

        uni.showToast({
          title: '提交成功',
          complete: function () {
            setTimeout(() => {
              uni.$u.route({
                type: 'navigateBack',
                delta: 1
              })
            }, 1500)
          }
        })
      }, 500);
    })
    .catch((err: any) => {
      uni.showToast({
        title: err[0].message,
        icon: 'none'
      })
    })
}

// 获取性别
const sexOptions = ref<DictItemTypes[]>([])
const getSexOptions = async () => {
  const { data } = await dictData('sys_user_sex') // 获取字典中的数据
  sexOptions.value = data
}
getSexOptions()

// 跳转去选择机构
const goSelectCom = () => {
  if (unref(pageType) === PageTypeEnum.AUDIT) return
  uni.$u.route({
    type: 'navigateTo',
    url: '/pages/organization/organization',
    params: {
      isCheckPage: true
    }
  })
}

// 跳转去设置签名
const goSetSign = () => {
  uni.$u.route({
    type: 'navigateTo',
    url: 'pages/expert/signature'
  })
}

// 选择机构变化,查询机构详情,获取机构的deptId查询科室列表
watch(
  () => selectedCom.value,
  (newVal, oldVal) => {
    formData.value.com = newVal.cname
    formData.value.comId = newVal.id
    newVal.id && getDeptOptions()
  },
  { deep: true }
)

const deptOptions = ref<DictItemTypes[]>([])
const getDeptOptions = async () => {
  const _res = await companyDetails(unref(selectedCom).id) // 查询机构详情
  const _comObj = _res?.data
  if (!_comObj) {
    // 机构不存在
    formData.value.com = ''
    formData.value.comId = ''
    formData.value.deptId = undefined
    deptOptions.value = []
    return
  }
  const { data } = await getDeptList(_comObj.deptId) // 获取科室列表

  deptOptions.value = data.map((v: any) => {
    return {
      dictValue: v.deptId,
      dictLabel: v.deptName
    }
  })

  // 回显时,存在科室ID,该科室却被删除的场景下,去除ID,重新选择
  if (unref(formData).deptId) {
    let _item = unref(deptOptions).find(
      (v) => v.dictValue === unref(formData).deptId
    )
    formData.value.deptId = _item ? (_item.dictValue as number) : undefined
  }
}

const postOptions = ref<DictItemTypes[]>([])
const getPostOptions = async () => {
  const { data } = await getPostList() // 获取职称列表
  postOptions.value = data.map((v: any) => {
    return {
      dictValue: v.postId,
      dictLabel: v.postName
    }
  })
}
getPostOptions()

// 获取医生审核详情
const { setSelectCom, setPrescriptionSign } = expertStore
const getApExpertDetails = (id: number) => {
  if (!id) return
  apExpertDetails(id).then((res) => {
    formData.value = res.data;
    setPrescriptionSign(res.data.prescriptionSign); // 医生签名回显
    setSelectCom({ id: String(res.data.comId), cname: res.data.com }); // 选择机构回显
  })
}

// 编辑医生-回显
const getExpertInfo = (id: number) => {
  if (!id) return
  expertInfo(id).then((res) => {
    formData.value = res.data;
    setPrescriptionSign(res.data.prescriptionSign); // 医生签名回显
    setSelectCom({ id: String(res.data.comId), cname: res.data.com }) // 选择机构回显
  })
}

// 跳转修改医生
const goEditExpert = () => {
  uni.$u.route({
    type: 'redirectTo',
    url: '/pages/expert/editExport',
    params: {
      id: formData.value.expertId,
      pageType: PageTypeEnum.EDIT
    }
  })
};

// 页面类型 audit: 审核详情 edit: 修改医生 默认为注册医生
const pageType = ref(PageTypeEnum.ADD)
onLoad((options) => {
  setPrescriptionSign(""); // 清除签名
  pageType.value = options?.pageType ?? PageTypeEnum.ADD
  unref(pageType) === PageTypeEnum.AUDIT && getApExpertDetails(options?.id)
  unref(pageType) === PageTypeEnum.EDIT && getExpertInfo(options?.id)
  if (options?.comId) {
    companyDetails(options?.comId).then((res) => {
      setSelectCom({ id: String(res.data.id), cname: res.data.cname })
    })
  }

  switch (unref(pageType)) {
    case PageTypeEnum.AUDIT:
      uni.setNavigationBarTitle({
        title: '审核详情'
      })
      break
    case PageTypeEnum.EDIT:
      uni.setNavigationBarTitle({
        title: '修改医生信息'
      })
      break
    default:
      uni.setNavigationBarTitle({
        title: '注册医生'
      })
      break
  }
})
onUnload(() => {
  setSelectCom({ id: '', cname: '' }) // 清除选择的机构
})
</script>

<style lang="scss" scoped>
</style>
